package com.hanyizhu.demostore.service.impl;

import com.hanyizhu.demostore.entity.Address;
import com.hanyizhu.demostore.entity.Order;
import com.hanyizhu.demostore.entity.OrderItem;
import com.hanyizhu.demostore.mapper.OrderMapper;
import com.hanyizhu.demostore.service.IAddressService;
import com.hanyizhu.demostore.service.ICartService;
import com.hanyizhu.demostore.service.IOrderService;
import com.hanyizhu.demostore.service.ex.InserException;
import com.hanyizhu.demostore.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author lenovo
 */
@Service
public class IOrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private ICartService cartService;

    @Override
    public Order create(Integer aid, Integer uid, String username, Integer... cids) {
        List<CartVO> list = cartService.getVoByCid(uid, cids);
        //计算商品的总价
        Long totalPrice = 0L;
        //创建详细项订单数据
        for (CartVO c:list
             ) {
            totalPrice += c.getNum()*c.getRealPrice();
        }
        Address address = addressService.getByAid(aid, uid);
        Order order = new Order();
        order.setUid(uid);
        //收货地址形象
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvCity(address.getCityName());
        order.setRecvArea(address.getAreaName());
        order.setRecvAddress(address.getAddress());
        order.setTotalPrice(totalPrice);
        order.setStatus(0);
        order.setOrderTime(new Date());
        order.setCreatedTime(new Date());
        order.setCreatedUser(username);
        order.setModifiedTime(new Date());
        order.setModifiedUser(username);
        //查询数据
        Integer rows = orderMapper.insertOrder(order);
        if (rows !=1){
            throw new InserException("插入时异常");
        }

        //创建一个订单项数据对象
        for (CartVO c :list) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOid(order.getOid());
            orderItem.setPid(c.getPid());
            orderItem.setTitle(c.getTitle());
            orderItem.setNum(c.getNum());
            orderItem.setPrice(c.getPrice());
            orderItem.setImage(c.getImage());

            //日志
            orderItem.setCreatedTime(new Date());
            orderItem.setCreatedUser(username);
            orderItem.setModifiedTime(new Date());
            orderItem.setModifiedUser(username);

            Integer integer = orderMapper.insertOrderItem(orderItem);
            if (integer != 1){
                throw new InserException("插入时产生了未知的异常");
            }
        }


        return order;
    }
}
